<template>
  <div class="video-upload-page">
    <div class="page-header">
      <h2>课件视频上传</h2>
      <p>预览支持 MP4、WebM、MOV、AVI 格式，单文件不超过 200MB</p>
    </div>

    <!-- 上传区域 -->
    <div class="upload-area">
      <el-upload
        class="upload-dragger"
        :action="url"
        :auto-upload="false"
        :on-change="handleFileChange"
        :file-list="fileList"
        :before-remove="handleBeforeRemove"
        drag
        accept="video/mp4,video/webm,video/quicktime,video/x-msvideo"
      >
        <i class="el-icon-video-camera"></i>
        <div class="el-upload__text">
          点击或拖拽视频文件到此处上传<br>
          <em>支持 MP4、WebM、MOV、AVI 格式</em>
        </div>
      </el-upload>

      <!-- 上传控制按钮 -->
      <div class="upload-controls" v-if="fileList.length > 0">
        <el-button
          type="primary"
          @click="handleBatchUpload"
          :loading="isUploading"
          :disabled="isUploading || fileList.length === 0"
        >
          <i class="el-icon-upload" v-if="!isUploading"></i>
          <i class="el-icon-loading" v-if="isUploading"></i>
          开始上传
        </el-button>
        <el-button
          type="warning"
          @click="clearAllFiles"
          :disabled="isUploading"
        >
          清空列表
        </el-button>
      </div>
    </div>

    <!-- 上传列表与预览 -->
    <div class="upload-list" v-if="fileList.length > 0">
      <el-table
        :data="fileList"
        border
        style="width: 100%; margin-top: 20px"
      >
        <el-table-column label="视频预览" width="200">
          <template #default="scope">
            <video
              :src="scope.row.url"
              width="180"
              height="100"
              controls
              preload="metadata"
              v-if="scope.row.url"
            ></video>
            <div class="preview-placeholder" v-else>
              <i class="el-icon-video-camera"></i>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="文件名" width="300">
          <template #default="scope">
            <div class="file-name" :title="scope.row.name">{{ scope.row.name }}</div>
          </template>
        </el-table-column>
        <el-table-column label="文件大小">
          <template #default="scope">{{ formatFileSize(scope.row.size) }}</template>
        </el-table-column>
        <el-table-column label="格式">
          <template #default="scope">{{ getFileExtension(scope.row.name) }}</template>
        </el-table-column>
        <el-table-column label="状态">
          <template #default="scope">
            <el-progress
              v-if="scope.row.uploading"
              :percentage="scope.row.progress"
              stroke-width="4"
              width="120"
            ></el-progress>
            <el-tag type="success" v-if="scope.row.status === 'success'">已完成</el-tag>
            <el-tag type="danger" v-if="scope.row.status === 'error'">上传失败</el-tag>
            <el-tag type="info" v-if="!scope.row.uploading && !scope.row.status">待上传</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button
              type="text"
              icon="el-icon-delete"
              @click="handleRemove(scope.$index, scope.row)"
              :disabled="scope.row.uploading"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import {getToken} from "@/utils/auth";

export default {
  data() {
    return {
      fileList: [], // 视频文件列表
      isUploading: false, // 整体上传状态
      uploadQueue: [],  // 上传队列（用于控制并发）
      // 上传的地址
      // url: process.env.VUE_APP_BASE_API + "/common/uploadVideo",
      url: process.env.VUE_APP_BASE_API + "/common/uploadVideoTest",
    };
  },
  methods: {
    // 处理文件选择
    handleFileChange(file, fileList) {
      // 过滤重复文件
      const uniqueFiles = fileList.filter((f, index) => {
        return fileList.findIndex(item => item.name === f.name && item.size === f.size) === index;
      });

      // 验证文件并生成预览
      uniqueFiles.forEach(f => {
        if (!f.verified) {
          this.verifyFile(f);
          f.verified = true;
        }
        // 生成预览 URL
        if (f.raw && !f.url) {
          f.url = URL.createObjectURL(f.raw);
          // console.log(f.url);
        }
      });

      this.fileList = uniqueFiles;
      // console.log(this.fileList);
    },

    // 文件验证（格式、大小）
    verifyFile(file) {
      const allowedTypes = ['video/mp4', 'video/webm', 'video/quicktime', 'video/x-msvideo'];
      const maxSize = 200 * 1024 * 1024; // 200MB

      // 验证格式
      // if (!allowedTypes.includes(file.raw.type)) {
      //   this.$message.error(`文件 ${file.name} 格式不支持，请上传 MP4、WebM、MOV 或 AVI 格式`);
      //   this.handleRemove(this.fileList.indexOf(file), file);
      //   return false;
      // }

      // 验证大小
      if (file.size > maxSize) {
        this.$message.error(`文件 ${file.name} 超过 200MB 限制`);
        this.handleRemove(this.fileList.indexOf(file), file);
        return false;
      }

      return true;
    },

    // 批量上传
    handleBatchUpload() {
      this.isUploading = true;
      // 并发上传（最多同时上传2个，避免请求拥堵）
      const concurrency = 2;
      this.uploadQueue = [...this.fileList];
      this.startUpload(concurrency);
    },

    // 递归上传队列
    startUpload(concurrency) {
      if (this.fileList.length === 0) {
        this.isUploading = false;
        return;
      }

      let count = 0;
      while (count < concurrency && this.fileList.length > 0) {
        const file = this.fileList.shift();
        this.uploadFile(file);
        count++;
      }
    },

    // 单个文件上传
    uploadFile(file) {
      const formData = new FormData();
      formData.append('file', file.raw); // 与后端参数名保持一致

      // 更新文件状态
      file.uploading = true;
      file.progress = 0;
      file.status = '';

      axios.post(this.url, formData, {
        headers: { Authorization: "Bearer " + getToken() },
        withCredentials: true,
        onUploadProgress: (progressEvent) => {
          // 计算上传进度
          file.progress = Math.round((progressEvent.loaded / progressEvent.total) * 100);
        }
      }).then(response => {
        if (response.data.code === 200) {
          file.status = 'success';
          this.$message.success(`文件 ${file.name} 上传成功`);
          console.log(response);
        } else {
          file.status = 'error';
          this.$message.error(`文件 ${file.name} 上传失败：${response.data.msg}`);
        }
      }).catch(error => {
        file.status = 'error';
        this.$message.error(`文件 ${file.name} 上传失败：网络异常`);
        // console.error(error);
      }).finally(() => {
        file.uploading = false;
        // 继续上传队列中的文件
        this.startUpload(1);
      });
    },

    // 移除单个文件
    handleRemove(index, file) {
      // 释放预览 URL
      if (file.url) {
        URL.revokeObjectURL(file.url);
      }
      this.fileList.splice(index, 1);
    },

    // 移除前确认
    handleBeforeRemove(file) {
      if (file.uploading) {
        this.$message.warning('正在上传的文件无法删除');
        return false;
      }
      return this.$confirm(`确定要删除 ${file.name} 吗？`);
    },

    // 清空所有文件
    clearAllFiles() {
      this.$confirm('确定要清空所有文件吗？').then(() => {
        // 释放所有预览 URL
        this.fileList.forEach(file => {
          if (file.url) {
            URL.revokeObjectURL(file.url);
          }
        });
        this.fileList = [];
      });
    },

    // 格式化文件大小
    formatFileSize(size) {
      if (size < 1024) return `${size} B`;
      if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`;
      return `${(size / (1024 * 1024)).toFixed(1)} MB`;
    },

    // 获取文件扩展名
    getFileExtension(filename) {
      return filename.split('.').pop().toUpperCase();
    }
  },
  beforeDestroy() {
    // 组件销毁时释放所有预览 URL
    this.fileList.forEach(file => {
      if (file.url) {
        URL.revokeObjectURL(file.url);
      }
    });
  }
};
</script>

<style scoped>
.video-upload-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-header h2 {
  color: #333;
  margin-bottom: 10px;
}

.page-header p {
  color: #666;
  font-size: 14px;
}

.upload-area {
  background: #fff;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.upload-dragger {
  border: 2px dashed #ddd;
  padding: 50px 20px;
  text-align: center;
  transition: border-color 0.3s;
}

.upload-dragger:hover {
  border-color: #409eff;
}

.upload-controls {
  margin-top: 20px;
  display: flex;
  gap: 10px;
}

.upload-list {
  margin-top: 30px;
}

.file-name {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.preview-placeholder {
  width: 180px;
  height: 100px;
  background-color: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
}

/* 视频预览样式优化 */
video {
  object-fit: contain;
  background-color: #000;
  border-radius: 4px;
}
</style>
